<?php

namespace app\mini\controller\driver;

use app\common\controller\ApiController;
use app\common\enum\order\OrderType;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\company\model\CompanyOrder;
use app\Request;
use think\App;
use think\response\Json;
use app\common\model\Store as StoreModel;

/**
 * @ControllerAnnotation(title="门店管理")
 */
class Store extends ApiController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new StoreModel;
    }

    public function listNew()
    {
        $get = $this->request->get();
        $where = [
            ['company_id', '=', $this->userInfo['company_id']],
        ];
        if(!empty($get['name'])){
            $where[] = ['name','like','%'.$get['name'].'%'];
        }
        if(!empty($get['lng']) && !empty($get['lat'])){
            $distance = distance($get['lng'],$get['lat']);
        }else{
            $distance = "'位置未知' AS distance";
        }
        $field = "*,{$distance}";
        $list = (new StoreModel())->field($field)->order('distance');
        $list = $list->where($where)->paginate($get['limit'] ?? 15)->toArray();
        return $this->success($list);
    }

    /**
     * 别删除，说不定我还得改回去
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function list(): Json
    {

        $get   = $this->request->get();
        $page = $get['page']??1;
        $limit = $get['limit']??10;
        $where = [
            ['pid', '<>', 0],
            ['order_type', '=', OrderType::SALES],
            ['driver_id', '=', $this->uid],
            ['check_status', '=', 2]
        ];
        if (!empty($get['name'])) {
            $where[] = ['store_id', 'in', $this->model->where('name', 'like', '%' . $get['name'] . '%')->column('id')];
        }
        $list = [];
        // 获取订单列表
        (new CompanyOrder())->field('*, sum(order_amount), sum(driver_money)')->where($where)->group('store_id')->select()
            ->each(function ($item) use (&$list, $where, $get) {
                // 获取该门店订单ids
                $where[]  = ['store_id', '=', $item->store_id];
                $orderIds = (new CompanyOrder())->where($where)->column('id');
                if (!empty($get['lon']) && !empty($get['lat'])) {
                    $distance = distance($get['lon'], $get['lat']);
                } else {
                    $distance = "'位置未知' AS distance";
                }
                $storeInfo = $this->model->field("lon,lat,{$distance},name,contact,phone,address")->where('id', $item->store_id)->find();
                $list[]    = [
                    'store_id'     => $item->store_id,
                    'store'        => $storeInfo->name,
                    'lon'          => $storeInfo->lon,
                    'lat'          => $storeInfo->lat,
                    'contact'      => $storeInfo->contact,
                    'phone'        => $storeInfo->phone,
                    'address'      => $storeInfo->address,
                    'order_amount' => $item['sum(order_amount)'],
                    'orderIds'     => implode(',', $orderIds),
                    'order_num'    => count($orderIds),
                    'driver_money' => $item['sum(driver_money)'],
                    'distance'     => $storeInfo['distance'],
                ];
            });
        $total = count($list);
        $list = array_slice($list, ($page - 1) * $limit, $limit);
        return $this->success(compact('list','total'));
    }

    /**
     * @NodeAnnotation(title="门店编辑")
     * @param Request $request
     * @return Json
     * @throws \app\common\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $info = $this->model->where('id', $post['id'])->find();
        if (empty($info)) return $this->error('门店不存在');
        try {
            $this->model->transaction(function ()use($info,$post){
                $info->save($post);
            });
        }catch (\Exception $e){
            return $this->error('修改成功'.$e->getMessage());
        }
        return $this->success('修改成功');
    }
}